﻿using System;
using System.Collections.Generic;

namespace Chimp.Core
{
    public class Expr : JointNode
    {
        public List<Var> Op = new List<Var>();

        public Expr(JointNode p)
        {
            SetData(p);
        }

        public override void WriteOutput()
        {
            _cw.Write("(");
            foreach (Var o in Op)
            {
                if (o.Exprs.Count > 0)
                {
                    string e = "(";
                    string s = ")";
                    if (o.IsArray)
                    {
                        e = "[";
                        s = "]";
                    }
                    _cw.Write(o.Name + e);
                    int i = 0;
                    foreach (JointNode p in o.Exprs)
                    {
                        p.WriteOutput();
                        if (i < o.Exprs.Count - 1)
                        {
                            _cw.Write(",");
                        }
                        i++;
                    }
                    _cw.Write(s);
                }
                else
                {
                    _cw.Write(o.Name);
                }
            }
            _cw.Write(")");
 
        }

        public override void ParseNode()
        {
            Console.WriteLine("Expr===="+PeekTok());
          
            int ei = 0;
            while (!Eof)
            {
                string t = PeekTok();
                if (t == ")")
                {
                    ei--;
                    if ( ei <1 )
                    {
                        GetTok();
                        Op.Add(new Var(")",""));
                        return;
                    }
                }
                if(t=="(")
                {
                    ei++;
                }
            
                GetTok();
       
                Op.Add(new Var(t, ""));
                if (PeekTok() == "[")
                {
                    Console.WriteLine("Array in...");
                    GetTok();
                    Op[Op.Count - 1].IsArray = true;
                    Op[Op.Count - 1].Exprs.Add(ParseExpr());
                    if (GetTok() != "]")
                    {
                        Console.WriteLine("Expecting \"]\".");
                        return;
                    }
                }
            }
        }
    }
}